/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.simulation;
import java.awt.CheckboxMenuItem;
import java.awt.MenuBar;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.TextArea;
import java.io.File;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.nio.CharBuffer;
/**
 *
 * @author 29159
 */
public class MenuList extends MenuBar{
    String path;//自动保存的存储路径
    static CheckboxMenuItem g,b;//需要在其他类中调用的组件
    public MenuList(){
        //file下拉菜单
        Menu file = new Menu("file");
        MenuItem open = new MenuItem("打开");
        MenuItem save = new MenuItem("保存");
        MenuItem saveAs = new MenuItem("另存为");
        MenuItem exit = new MenuItem("退出");
        save.setEnabled(false);//开始时未读入路径，故将save设为不可用
        TextArea ta = new TextArea();//实例化一个隐藏的TextArea，不将其加入任何frame中，用于存储文件内容
        //打开的事件处理
        open.addActionListener((ActionEvent e) -> {
            JFileChooser chooser = new JFileChooser("请选择文件");
            FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(*.txt)", "txt");
            chooser.setFileFilter(filter);
            int res = chooser.showOpenDialog(null);
            if (res == JFileChooser.APPROVE_OPTION) {
                File file1 = chooser.getSelectedFile();
                path = file1.getAbsolutePath();
                try {
                    CharBuffer cb;
                    try (final InputStreamReader reader = new InputStreamReader(new FileInputStream(path), "utf-8")) {
                        char[] buf = new char[1024];
                        int len = 0;
                        cb = CharBuffer.allocate((int) file1.length());
                        while((len = reader.read(buf)) > -1){
                            cb.put(buf, 0, len);
                        }
                    }
                    String str = new String(cb.array());//str用于存储txt文件内容
                    String [] arr = str.split(" ");//将str以" "进行分割
                    Spring.set(Double.parseDouble(arr[0]),Double.parseDouble(arr[1]),Double.parseDouble(arr[2]),Double.parseDouble(arr[3]),Double.parseDouble(arr[4]));//调用Spring类的static方法
                    frame.t1.setText(arr[2]);//调用frame类的static成员
                    frame.t2.setText(arr[3]);
                    frame.t3.setText(arr[0]);
                    frame.t4.setText(arr[1]);
                    frame.t5.setText(arr[4]);
                    ta.setEditable(false);
                    ta.setText(str);//将str存入隐藏的TextArea中
                    save.setEnabled(true);//当进行过读入后，将save设为可用
                }catch (IOException | NumberFormatException e1) {
                }
            }
        });
        //保存的事件处理
        save.addActionListener((ActionEvent e) -> {
            String str1,str2,str3,str4,str5;
            str1=frame.t1.getText();
            str2=frame.t2.getText();
            str3=frame.t3.getText();
            str4=frame.t4.getText();
            str5=frame.t5.getText();
            //对文本框内的字符串进行正则表达式验证，当全部为实数再继续存储
            if(str1.matches("-?[0-9]+.?[0-9]{0,}")&&str2.matches("-?[0-9]+.?[0-9]{0,}")&&str3.matches("-?[0-9]+.?[0-9]{0,}")&&str4.matches("-?[0-9]+.?[0-9]{0,}")&&str5.matches("-?[0-9]+.?[0-9]{0,}")){
                String content = frame.t3.getText()+" "+frame.t4.getText()+" "+frame.t1.getText()+" "+frame.t2.getText()+" "+frame.t5.getText();
                try {
                    try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), "gbk") //打开事件中已经将路径储存至path
                            ) {
                        writer.write(content);
                    }
                } catch (IOException e1) {
                }
            }
            //若不全部为实数则警告
            else{
                JFrame Alert = new JFrame("Alert");
                JLabel l = new JLabel("请保证全部数据框内均为实数");
                l.setSize(2000, 30);
                Alert.add(l);
                Alert.setLayout(null);
                Alert.setBounds(600, 400, 200, 70);
                Alert.setVisible(true);
            }
        });
        //另存为的事件处理
        saveAs.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String str1,str2,str3,str4,str5;
                str1=frame.t1.getText();str2=frame.t2.getText();str3=frame.t3.getText();str4=frame.t4.getText();str5=frame.t5.getText();
                if(str1.matches("-?[0-9]+.?[0-9]{0,}")&&str2.matches("-?[0-9]+.?[0-9]{0,}")&&str3.matches("-?[0-9]+.?[0-9]{0,}")&&str4.matches("-?[0-9]+.?[0-9]{0,}")&&str5.matches("-?[0-9]+.?[0-9]{0,}")){
                    String content = frame.t3.getText()+" "+frame.t4.getText()+" "+frame.t1.getText()+" "+frame.t2.getText()+" "+frame.t5.getText();
                    JFileChooser chooser = new JFileChooser();
                    FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(*.txt)", "txt");
                    chooser.setFileFilter(filter);
                    int res =chooser.showSaveDialog(null);
                    if(res == JFileChooser.APPROVE_OPTION){
                        path = chooser.getSelectedFile().getAbsolutePath() + ".txt";
                        try {
                            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), "gbk");
                            writer.write(content);
                            writer.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
                else{
                    JFrame Alert = new JFrame("Alert");
                    JLabel l = new JLabel("请保证全部数据框内均为实数");
                    l.setSize(200, 30);
                    Alert.add(l);
                    Alert.setLayout(null);
                    Alert.setBounds(600, 400, 200, 70);
                    Alert.setVisible(true);
                }
            }
        });
        //退出的事件处理
        exit.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
            
        });
        file.add(open);
        file.add(save);
        file.add(saveAs);
        file.addSeparator();//增加分隔符
        file.add(exit);
        //Control的下拉菜单
        Menu control = new Menu("Control");
        g = new CheckboxMenuItem("忽略重力");
        b = new CheckboxMenuItem("忽略阻尼");
        //忽略重力的事件处理（未实现，预估原因为CheckboxMenuItem类不支持ActionListener）
        g.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                JFrame alert = new JFrame("Alert");
                alert.setSize(300,400);
                alert.setLocation(800, 500);
                alert.setLayout(null);
                alert.setVisible(true);
                String f;
                if(g.getState()){
                    frame.t5.setEditable(false);
                    f="<html><body>已忽略重力影响</body></html>";
                }
                else{
                    frame.t5.setEditable(true);
                    f="<html><body>已恢复物体重力</body></html>";
                }
                JLabel f1 = new JLabel(f);
                f1.setBounds(50, 0, 200, 400);
                alert.add(f1);
            }
        });
        //忽略阻尼的事件处理（未实现，预估原因为CheckboxMenuItem类不支持ActionListener）
        b.addActionListener((ActionEvent e) -> {
            if(b.getState()){
                JFrame alert = new JFrame("Alert");
                alert.setSize(300,400);
                alert.setLocation(800, 500);
                alert.setLayout(null);
                alert.setVisible(true);
                String f;
                f="<html><body>运动将一直持续下去</body></html>";
                JLabel f1 = new JLabel(f);
                f1.setBounds(50, 0, 200, 400);
                alert.add(f1);
                frame.t2.setEditable(false);
            }
            else{
                frame.t2.setEditable(true);
            }
        });
        control.add(g);
        control.add(b);
        //Help的下拉菜单
        Menu Help = new Menu("Help");
        MenuItem help = new MenuItem("帮助");
        MenuItem form = new MenuItem("数据格式");
        //帮助的事件处理
        help.addActionListener((ActionEvent e) -> {
            JFrame help1 = new JFrame("Help");
            help1.setSize(300, 300);
            help1.setLocation(600, 500);
            help1.setLayout(null);
            help1.setVisible(true);
            String h = "<html><body style=\"text-align:center\">Copyright © 2019-2021nenu<br><br>Preasent by TinnyCatLen<br><br>E-mail:TinnyCatLen@outlook.com<br><br>Object oriented programming 侯鲲<br><br>Thanks for Speciality sml.n@qq.com</body></html>";
            JLabel h1 = new JLabel(h);
            h1.setBounds(40, 0, 300, 300);
            help1.add(h1);
        });
        //数据格式的事件处理
        form.addActionListener((ActionEvent e) -> {
            JFrame form1 = new JFrame("Form");
            form1.setSize(300, 300);
            form1.setLocation(800, 500);
            form1.setLayout(null);
            form1.setVisible(true);
            String f = "<html><body style=\"text-align:center\">若要编辑信息文件<br>请将变量按照以下顺序输入<br>并以空格作为分隔符<br>质量、长度、刚度、阻尼、重力加速度<br><br>示例：<br>0.25 250 10 0.4 8</body></html>";
            JLabel f1 = new JLabel(f);
            f1.setBounds(40, 0, 240, 300);
            form1.add(f1);
        });
        Help.add(help);
        Help.add(form);
        //version的下拉菜单
        Menu version = new Menu("Version");
        MenuItem ver = new MenuItem("版本信息");
        //版本信息的事件处理
        ver.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                JFrame version = new JFrame("日志");
                version.setSize(500,300);
                version.setLocation(400, 200);
                version.setLayout(null);
                version.setVisible(true);
                String ver ="<html><body style=\"text-align:center\">ver1.0 swing创建窗口，重写print方法"
                        + "<br>ver1.1 实现Runnable接口，用线程实现动画效果"
                        + "<br>ver1.2 为Spring面板增加mouselistener，实现拖动改变物块位置"
                        + "<br>"
                        + "<br>ver2.0 增加menulist，实现顶部菜单"
                        + "<br>ver2.1 使用IO流读写文件，实现数据的读取与存储"
                        + "<br>ver2.2 使用正则表达式判断数据输入，实现数据审核"
                        + "<br>ver2.3 增加顶部可调选项，实现对阻尼、重力加速度的控制"
                        + "<br>ver2.4 增加可调弹簧段数设置"
                        + "</body></html>";
                JLabel lab = new JLabel(ver);
                lab.setSize(500, 300);
                lab.setLocation(65,0);
                version.add(lab);
           }
        });
        version.add(ver);
        //将组建加入MenuBar中
        this.add(file);
        this.add(control);
        this.add(Help);
        this.add(version);
    }
}
